package cn.tedu._07springaop.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect
@Component
public class LogAspect {

//    @Before("execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))")
//    public void beforeMethod(JoinPoint joinPoint) {
//        System.out.println("1.前置通知：\n " + joinPoint.getSignature().getName() + "方法开始，参数为:" + Arrays.toString(joinPoint.getArgs()));
//    }
//
//    @AfterReturning(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))",returning = "result")
//    public void afterReturningMethod(JoinPoint joinPoint,Object result) {
//        System.out.println("2.返回通知:(方法执行成功)\n " + joinPoint.getSignature().getName() + "方法结束, 返回值为" + result.toString());
//    }
//    @AfterThrowing(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))",throwing = "e")
//    public void afterThrowingMethod(JoinPoint joinPoint,Throwable e) {
//        String name = joinPoint.getSignature().getName();
//        System.out.println("3.异常通知:(方法执行失败)\n " + name + "方法执行失败, 异常信息为" + e.getMessage());
//    }

    @Around("execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))")
    public Object aroundMethod(ProceedingJoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();
        Object result = null;
        try {
            System.out.println("1.前置通知：\n " + name + "方法开始，参数为:" + Arrays.toString(joinPoint.getArgs()));
            result = joinPoint.proceed();
            System.out.println("2.返回通知:(方法执行成功)\n " + name + "方法结束, 返回值为" + result.toString());
        } catch (Throwable e) {
            String message = e.getMessage();
            System.out.println("3.异常通知:(方法执行失败)\n " + name + "方法执行失败, 异常信息为" + message);
        } finally {
        System.out.println("4.后置通知:(方法执行结束)\n " + name + "方法结束");
        }
        return result;
    }
}

